<?php

namespace Core\annotationshandlers;

use Core\annotations\RequestMapping;
use Core\BeanFactory;

return [
    RequestMapping::class => function (\ReflectionMethod $method, $instance, $self) {
        $path = $self->value;
        $request_method = count($self->method) > 0 ? $self->method : ["GET"];
        $router_collect = BeanFactory::getBean('RouterCollect');
        $router_collect->addRouter($request_method, $path, function ($params,$ext_params) use ($instance, $method) {
            /**
             * 执行反射方法,不会传递参数直接调用的
             */
            //return $method->invoke($instance);

            /**
             * 执行反射方法,能够传递参数的调用
             */
            $inputParams = [];
            $ref_params = $method->getParameters();
            foreach ($ref_params as $ref_param) {
                if (isset($params[$ref_param->getName()])) {
                    $inputParams[] = $params[$ref_param->getName()];
                } else {
                    //都是实例对象
                    foreach ($ext_params as $ext_param){
                        if ($ref_param->getClass()->isInstance($ext_param)){
                            $inputParams[] = $ext_param;
                            goto content_end;
                        }
                    }
                    $inputParams[] = false;
                }
                content_end:
            }
            return $method->invokeArgs($instance, $inputParams);
        });
        return $instance;
    }
];
